<?php

namespace App\BO;

use Symfony\Component\PropertyAccess\PropertyAccess;

class PropertyAccessAndSetBO
{
    /**
     * @return \Symfony\Component\PropertyAccess\PropertyAccessorInterface
     */
    private static function getAccessor()
    {
        $propertyAccessorBuilder = PropertyAccess::createPropertyAccessorBuilder();
        $propertyAccessorBuilder->disableExceptionOnInvalidPropertyPath();

        return $propertyAccessorBuilder->getPropertyAccessor();
    }

    /**
     * @param $obj
     * @return array
     */
    public static function getKeys($obj)
    {
        return array_keys(get_object_vars($obj));
    }

    /**
     * @param $src
     * @param $target
     * @param array $keys  要同步的属性名
     * @return mixed
     */
    public static function sync($src, $target, array $keys = [])
    {
        $accessor = self::getAccessor();

        if (empty($keys)) {
            $keys = self::getKeys($target);
        }
        foreach ($keys as $key) {
            $value = $accessor->getValue($src, $key);
            if (!is_null($value)) {
                $accessor->setValue($target, $key, $value);
            }
        }

        return $target;
    }
}
